import {createRouter, createWebHashHistory} from 'vue-router'
import useUserStore from '../stores/user.js'

// 导入视图组件
import Login from '../views/login/Login.vue'
import Regis from '../views/regis/Regis.vue'
import Index from '../views/index/Index.vue'
import DeviceManage from '../views/deviceManage/DeviceManage.vue'
import Report from '../views/report/Report.vue'
import Task from '../views/task/Task.vue'

const routes = [
    {
        path: '/login',
        name: 'Login',
        component: Login,
        meta: {
            title: '登录'
        }
    },
    {
        path: '/regis',
        name: 'Regis',
        component: Regis,
        meta: {
            title: '注册'
        }
    },


    {
        path: '/',
        component: () => import('../layout/Layout.vue'),
        name: 'layout',
        redirect: '/index',
        children: [
            {
                path: 'index',
                name: 'Index',
                component: Index,
                meta: {
                    title: '首页',
                    icon: 'icon-home'
                }
            },
            {
                path: 'task',
                name: 'Task',
                component: Task,
                meta: {
                    title: '测评任务',
                    icon: 'icon-renwujincheng'
                }
            },
            {
                path: 'report',
                name: 'Report',
                component: Report,
                meta: {
                    title: '测评报表',
                    icon: 'icon-baobiao'
                }
            },
            {
                path: 'device',
                name: 'DeviceManage',
                component: DeviceManage,
                meta: {
                    title: '设备管理',
                    icon: 'icon-shezhi'
                }
            },
        ]
    },

]

const router = createRouter({
    history: createWebHashHistory(),
    routes
})

// 全局导航守卫 - 设置页面标题
router.beforeEach((to, from, next) => {
    const userStore = useUserStore()
    if(!userStore?.token?.token && to.path !== '/login' && to.path !== '/regis') {
        next({ path: '/login' })
        return
    }
    const title = to.meta.title
    if (title) {
        document.title = `${title}`
    }
    next()
})

export default router